/*
 * Copyright 2010 Christoph Widulle (christoph.widulle@googlemail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */



package com.android1.amarena2d.commons.collections;


/**
 * NOT Threadsafe.
 *
 * @param <E>
 */
public class FixedSizeQueue<E> {

    private static final int INITIAL_SIZE = 10;

    private final int size;
    private int headIndex;
    private int insertIndex;
    private final E[] elements;
    private int lenght;

    public FixedSizeQueue() {
        this(INITIAL_SIZE);
    }

    public FixedSizeQueue(int size) {
        this.size = size;
        this.elements = (E[]) new Object[size];
    }

    public boolean add(E o) {
        if (elements[insertIndex] == null) {
            elements[insertIndex] = o;
            insertIndex = inc(insertIndex);
            lenght++;
            return true;
        } else {
            return false;
        }
    }

    //todo optimize me

    public boolean contains(E e) {
        for (int i = 0; i < elements.length; i++) {
            E element = elements[i];
            if (element != null && element.equals(e))
                return true;
        }
        return false;
    }

    public E poll() {
        E e = elements[headIndex];
        if (e != null) {
            elements[headIndex] = null;
            headIndex = inc(headIndex);
            lenght--;
        }
        return e;
    }

    public int length() {
        return lenght;
    }

    private int inc(int index) {
        if (index == size - 1)
            index = 0;
        else
            index++;
        return index;

    }

    public void clear() {
        for (int i = 0; i < elements.length; i++) {
            elements[i] = null;
        }
        headIndex = 0;
        insertIndex = 0;
        lenght = 0;

    }

    public E peek() {
        return elements[headIndex];
    }
}

